import WebSocket from 'ws'
import { getWindow } from './windowProxy'
import { ElMessage } from 'element-plus'

const NODE_ENV = process.env.NODE_ENV

let ws = null
let wsUrl = 'ws:/127.0.0.1:2026/ws'
let mainWindowsSender = null
let needReconnect = true
let maxReConnectTimes = 5
let lockReconnect = false

/**
 * 初始化ws
 * @param{{token:string}} config   token
 * @param{WebContents} _sender  发送消息的窗口
 */
const initWs = (config, _sender) => {
  wsUrl = `${wsUrl}?token=${config.token}`
  mainWindowsSender = _sender
  createWs()
}
const closeWs = () => {
  needReconnect = false
  ws.close()
}

const createWs = () => {
  if (wsUrl == null) {
    return
  }
  ws = new WebSocket(wsUrl)
  ws.onopen = function(params) {
    console.log('客户端连接成功')
    ws.send('heart beat')
    maxReConnectTimes = 5
  }

  // 从服务器接受到信息时的回调函数
  ws.onmessage = async function(e) {
    let mainWindow = getWindow('main')
    //信息消息闪烁
    if (!mainWindow.isFocused()) {
      mainWindow.flashFrame(true)
    }
    console.log('收到ws服务器消息', e.data)
    const message = JSON.parse(e.data)
    const leaveGroupUserId = message.extendData
    const messageType = message.messageType
    if (messageType == 7) {
      //发送消息退出
      mainWindowsSender.send('allopatryLogin')
      closeWs()  //关闭ws连接
    }

    // case 7://异地登录 强制下线
    // case 0://ws链接成功
    // case 4://好友申请
    // case 6://文件上传完成
    // case 10://修改群昵称
    // case 1: //添加好友成功
    // case 3://群创建成功
    // case 9://好友加入群组
    // case 2://聊条消息
    // case 5://图片，视频消息
    // case 8://解散群聊
    // case 11://退出群聊
    // case 12://提出群聊


  }

  // 连接关闭后的回调函数存储数据
  ws.onclose = function(evt) {
    console.log('关闭客户端连接准备重连')
    reconnect('onclose')
  }

  // 连接失败后的回调函数
  ws.onerror = function(evt) {
    console.log('连接失败了准备重连')
    reconnect('onerror')
  }

  const reconnect = (type) => {
    if (!needReconnect) {
      console.log('链接断开无须重连')
      return
    }
    if (ws != null) {
      ws.close()
    }
    if (lockReconnect) {
      return
    }
    console.log(type + '准备重连')
    lockReconnect = true
    if (maxReConnectTimes > 0) {
      console.log('准备重连，剩余重连次数' + maxReConnectTimes, new Date().getTime())
      maxReConnectTimes--
      // 进行重连
      setTimeout(function() {
        createWs()
        lockReconnect = false
      }, 5000)
    } else {
      console.log('TCP连接已超时')
    }
  }

  //发送心跳
  setInterval(() => {
    if (ws != null && ws.readyState == 1) {
      ws.send('heart beat')
    }
  }, 1000 * 5)
}

export default {
  initWs,
  closeWs
}
